<template>
  <div class="service-info">
    <el-card v-loading="loading">
      <div class="tab-header">
        <span>服务监控</span>
        <el-icon class="refresh-icon" @click="refresh">
          <Refresh />
        </el-icon>
      </div>
      <el-table :data="info" border stripe>
        <el-table-column prop="name" label="服务名称" min-width="120" align="center" />
        <el-table-column prop="port" label="监听端口" min-width="100" align="center" />
        <el-table-column prop="version" label="版本信息" min-width="120" align="center" />
        <el-table-column prop="pid" label="进程ID" min-width="100" align="center" />
        <el-table-column prop="memory" label="内存占用" min-width="120" align="center" />
        <el-table-column prop="cpu" label="CPU使用率" min-width="120" align="center">
          <template #default="{ row }">
            <el-progress 
              :percentage="parseFloat(row.cpu)" 
              :format="percentageFormat"
              :status="getCpuStatus(row.cpu)"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { Refresh } from '@element-plus/icons-vue'
import { getServiceInfo, type ServiceInfo } from '/@/api/monitor'

const info = ref<ServiceInfo[]>([])
const loading = ref(false)

const percentageFormat = (percentage: number): string => `${percentage}%`

// 获取CPU使用率进度条状态
const getCpuStatus = (cpu: string): '' | 'success' | 'warning' | 'exception' => {
  const usage = parseFloat(cpu)
  if (usage < 50) return 'success'
  if (usage < 80) return 'warning'
  return 'exception'
}

const refresh = async () => {
  try {
    loading.value = true
    const { data } = await getServiceInfo()
    info.value = data.services
  } finally {
    loading.value = false
  }
}

defineExpose({
  refresh
})
</script>

<style lang="scss" scoped>
@import '../styles/common.scss';

.service-info {
  :deep(.el-progress) {
    margin: 0;
    width: 90%;
  }
}
</style> 